"use client";
import { useSidebarStore } from "@/components/state/sidebar_state";
import { FileUploadZone } from "@/components/comps/FileUpload";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { ComboboxDemo } from "@/components/custom/combobox";
import { Switch } from "@/components/ui/switch";
import { useEffect, useRef, useState } from "react";
import { redirect } from "next/navigation";
import { DataProps } from "@/components/models/dataprops";
import { postData } from "@/components/utils/api";
import { FastResponse, DataItem } from "@/components/models/dataprops";

const data_froms = [
  {
    label: "开源数据",
    value: "开源数据",
  },
  {
    label: "自建数据",
    value: "自建数据",
  },
];

interface DataRegisterProps<T> {
  code: number;
  data: T;
  msg: string;
}

function DataRegister() {
  const updateSelected = useSidebarStore((state) => state.updateSelected);
  updateSelected("数据注册", "数据中心");

  const [name, setName] = useState("");
  const [des, setDes] = useState("");
  const [uploader, setUploader] = useState("");
  const [dataType, setDataType] = useState("静态数据");
  const [dataFrom, setDataFrom] = useState("");
  const [dataPath, setDataPath] = useState("");

  const [uploaded, setUploaded] = useState(true);
  const [msg, setMsg] = useState("");
  const [success, setSuccess] = useState(false);

  // const router = useRouter();
  const isFirstRef = useRef(true);

  useEffect(() => {
    if (isFirstRef.current) {
      isFirstRef.current = false;
      return;
    }

    const timer = setTimeout(() => {
      redirect("/data/list");
    }, 3000);
    return () => clearTimeout(timer);
  }, [success]);

  const handle_upload = async () => {
    if (name === "") {
      setMsg("数据名不能为空!");
      return;
    }
    if (des === "") {
      setMsg("数据描述不能为空!");
      return;
    }
    if (uploader === "") {
      setMsg("维护人不能为空!");
      return;
    }
    if (dataFrom === "") {
      setMsg("数据来源不能为空!");
      return;
    }
    if (dataPath === "") {
      setMsg("数据地址不能为空!");
      return;
    }
    setMsg("");

    const payload: DataProps = {
      data_name: name,
      data_des: des,
      data_from: dataFrom,
      data_type: dataType,
      data_owner: uploader,
      data_path: dataPath,
    };
    try {
      const result = await postData<
        FastResponse<DataRegisterProps<DataItem>>,
        DataProps
      >("/data/register", payload);
      if (result.code === 200) {
        setMsg("数据注册成功，3秒后跳转到数据列表");
        setSuccess(true);
      }
    } catch (error) {
      console.log("Error submitting data:", error);
      setMsg("请求失败，请稍后重试");
    }
  };

  return (
    <div className="grid grid-cols-[150px_auto] items-center text-sm">
      <div className="p-4 pl-2 text-end"> 数据名：</div>{" "}
      <Input onChange={(e) => setName(e.target.value)} />
      <div className="p-4 pl-2 text-end"> 数据描述：</div>
      <Textarea
        placeholder="请输入数据描述"
        onChange={(e) => setDes(e.target.value)}
      />
      <div className="p-4 pl-2 text-end"> 维护人：</div>{" "}
      <Input onChange={(e) => setUploader(e.target.value)} />
      <div className="p-4 pl-2 text-end"> 数据来源：</div>{" "}
      <ComboboxDemo
        items={data_froms}
        placehoder="所有来源"
        onChange={setDataFrom}
      />
      <div className="p-4 pl-2 text-end"> 参与调优：</div>
      <Switch
        checked={dataType === "调优数据"}
        onCheckedChange={(checked) =>
          setDataType(checked ? "调优数据" : "静态数据")
        }
      />
      <div className="p-4 pl-2 text-end"> 数据已上传：</div>
      <Switch
        checked={uploaded}
        onCheckedChange={(checked) => {
          setUploaded(checked);
        }}
      />
      {!uploaded ? (
        <>
          <div className="p-6 pl-2 pr-4 text-end"> 选择文件：</div>
          <div>
            <FileUploadZone
              onFileUploaded={(path: string) => {
                setDataPath(path);
              }}
            />
          </div>
        </>
      ) : null}
      <div className="p-4 pl-2 text-end"> 数据地址：</div>{" "}
      <Input
        disabled={!uploaded}
        value={dataPath}
        onChange={(e) => {
          setDataPath(e.target.value);
        }}
      />
      <p></p>
      <div className="p-4 items-center">
        <button
          onClick={handle_upload}
          className="p-2 w-full bg-emerald-700 rounded-md text-gray-100 font-semibold text-sm hover:bg-green-700 hover:text-gray-50"
        >
          注册数据
        </button>
      </div>
      <p></p>
      <p className="pl-10 text-start font-semibold text-xs text-red-600">
        {msg}
      </p>
    </div>
  );
}

export default DataRegister;
